<template>
  <div class="mid-block1">
    <div class="midtab clearfix">
      <div class="tab-left">
        <swiper ref="swiperTop" class="swiper" :options="swiperOptionTop">
          <template v-for="(item, index) in playerList">
            <swiper-slide style="height: 450px">
              <video
                name="videox"
                width="800px"
                :id="'videoElement' + index"
                ref="myDiv"
                height="450px"
                class="vjs-default-skin vjs-big-play-centered"
                controls
                muted
                autoplay
              ></video>
            </swiper-slide>
          </template>
        </swiper>
      </div>

      <div class="tab-right" style="position: relative">
        <div class="prev" style="top: -10px">
          <i class="el-icon-caret-top" style="color: white" />
        </div>
        <swiper
          ref="swiperThumbs"
          class="swiper"
          :options="swiperOption"
          style="height: 410px; margin: 20px 0"
          @click-slide="handleClickSlide"
        >
          <template v-for="(item, index) in playerList">
            <swiper-slide
              style="height: 95px; position: relative"
              :class="{ active: active === index }"
            >
              <video
                class="demo-video1"
                :ref="'player1' + index"
                muted
                autoplay
              ></video>
              <div
                class="title text-ellipsis"
                style="
                  position: absolute;
                  color: #ffffff;
                  background: linear-gradient(
                    180deg,
                    rgba(0, 0, 0, 0) 0%,
                    rgba(0, 0, 0, 1) 100%
                  );
                  z-index: 10;
                  left: 0;
                  right: 0;
                  padding: 0 10px;
                  bottom: 0;
                  font-size: 12px;
                  height: 45px;
                  line-height: 70px;
                "
              >
                {{ item.name }}
              </div>
            </swiper-slide>
          </template>
        </swiper>
        <div class="next" style="bottom: -10px">
          <i class="el-icon-caret-bottom" style="color: white" />
        </div>
      </div>
    </div>
  </div>
</template>

<!-- <template>
  <div>
      <video class="demo-video" ref="player" muted autoplay></video>
  </div>
</template> -->
<script>
import flvjs from "flv.js";
import { postHandle } from "@/api";
import { Swiper, SwiperSlide, directive } from "vue-awesome-swiper";
import "swiper/css/swiper.css";
export default {
  components: {
    Swiper,
    SwiperSlide,
  },
  props: {
    newSpaceId: {
      type: String,
    },
  },
  data() {
    return {
      ii:1,
      playerList: [],
      videox: [],
      calleft: 0,
      videoElementx: [],
      active: 0,
      timer: null,
      player: [],

      playerOptions: [],
      swiperOptionTop: {
        loopedSlides: 5, // looped slides should be the same
        spaceBetween: 10,
      },
      swiperOption: {
        direction: "vertical",
        loopedSlides: 4, // looped slides should be the same
        spaceBetween: 10,
        slidesPerView: "auto",
        touchRatio: 0.2,
        slideToClickedSlide: true,
        height: 410,
        navigation: {
          nextEl: ".next",
          prevEl: ".prev",
        },
      },
    };
  },
  computed: {
    entSpaceId() {
      return this.$store.getters.entSpaceId;
    },
    spaceId() {
      return this.$store.getters.spaceId;
    },
  },
  watch: {
    newSpaceId(v) {
      if (v) this.getData();
    },
  },
  created() {
    //location.reload();
    this.getData();
    this.$nextTick(() => {});
  },
  beforeDestroy() {
    window.clearInterval(this.timer);
  },
  mounted() {
    let box;

    this.$nextTick(() => {});
  },
  beforeDestroy() {
    //this.player.destory();
  },
  methods: {
    timeStart() {
      this.time = setInterval(this.startTime, 5000);
    },
    stop() {
      console.log("暂停");
      clearInterval(this.time);
    },
    startTime() {
      this.player.forEach((item, index) => {
        try {
          if (this.player[index].buffered.length) {
            let end = this.player[index].buffered.end(0);
            let delta = end - this.player[index].currentTime;

            // 延迟过大，通过跳帧的方式更新视频
            if (delta > 3) {
              item.currentTime = item.buffered.end(0) - 1;
              return;
            }

            // 追帧
            if (delta > 1) {
              this.videoElementx[index].playbackRate = 1.1;
            } else {
              this.videoElementx[index].playbackRate = 1;
            }
          } else {
           
          }
        } catch (e) {
          console.log(e);
        }
        console.log("定时任务---------"+this.ii++);
        item.on( flvjs.Events.ERROR, (errType, errDetail) => {
          console.log(" 视频有异常...");
          console.log("errorType:", errType);
          console.log("errorDetail:", errDetail);
         
          //视频出错后销毁重新创建
          if (item) {
            try {
              item.pause();
              item.unload();
            item.detachMediaElement();
             item.destroy();
            } catch (e) {
              console.log(e);
            }
            item = null;
            if(this.ii>5){
              this.createdPlay(index, this.playerList[index].nwurl); 
            }
          }
        }
      );
      });
    },

    getData() {
      postHandle("/api/v1/welder-sbtx-second/video-comb/list", {
        d: {
          filters: [
            {
              field: "spaceId",
              operator: "EQUALS",
              value: this.newSpaceId || this.spaceId,
            },
          ],
          sorts: [{ field: "sequence", isDesc: false }],
        },
      }).then((res) => {
        this.playerList = res.result;
        this.$nextTick(() => {
          this.playerList.forEach((item, index) => {
            var videoElement = document.getElementById("videoElement" + index);
            if (flvjs.isSupported()) {
              var player = flvjs.createPlayer(
                {
                  type: "flv",
                  isLive: true,
                  hasAudio: false,
                  url: "rtmp://localhost:1935/live/dahua",
                },
                {
                  enableWorker: false, //不启用分离线程
                  enableStashBuffer: false, //关闭IO隐藏缓冲区
                  reuseRedirectedURL: true, //重用301/302重定向url，用于随后的请求，如查找、重新连接等。
                  autoCleanupSourceBuffer: true, //自动清除缓存
                }
              );
              player.attachMediaElement(videoElement);
              try {
                player.load();
                player.play();

                this.player.push(player);
                this.videoElementx.push(videoElement);
              } catch (error) {
                console.log(error);
              }
            }
          });
          this.timeStart();
        });
      });

      
    },

    handleClickSlide(e) {
      this.active = e;
      this.$nextTick(() => {
        const swiperTop = this.$refs.swiperTop.$swiper;
        swiperTop.slideTo(e, 1000, false);
      });
      //var videoElement = document.getElementById("videoElement"+index);
      // this.playerList.forEach((item, index) => {
      //   if (index == e) {
      //     this.player[index].play();
      //   } else {
      //     this.player[index].pause();
      //   }
      // });
    },
    createdPlay(index, url) {
      var videoElement = document.getElementById("videoElement" + index);
      if (flvjs.isSupported()) {
        let player1 = flvjs.createPlayer(
          {
            type: "flv",
            isLive: true,
            hasAudio: false,
            url: url,
          },
          {
            enableWorker: false, //不启用分离线程
            enableStashBuffer: false, //关闭IO隐藏缓冲区
            reuseRedirectedURL: true, //重用301/302重定向url，用于随后的请求，如查找、重新连接等。
            autoCleanupSourceBuffer: true, //自动清除缓存
          }
        );
        player1.attachMediaElement(videoElement);

        player1.load();
        player1.play();
        this.player[index] = player1;
      }
    },
  },
};
</script>
<style>
.demo-video {
  max-width: 800px;
  max-height: 450px;
}
.demo-video1 {
  max-width: 156px;
  max-height: 92px;
}
</style>
